//
//  LSZAudioSearchContentVC.m
//  JKFuYinProject
//
//  Created by 九酷 on 2018/4/13.
//  Copyright © 2018年 LC. All rights reserved.
//

#import "LSZAudioSearchContentVC.h"
//#import "LSZAudioSearchContentVC+LCAVPlay.h"
#import "NetworkTool+LCAVPlay.h"


#import "ZNBAttributedString.h"

@interface LSZAudioSearchContentVC ()
{
    LSZEmptyDataVC * vcResults;
    LSZEmptyDataVC * vcAlbum;
    LSZEmptyDataVC * vcSinger;
}
@property (assign,  nonatomic) bool isPop;
@property(nonatomic,strong) UITableView * tableViewResults;
@property(nonatomic,strong) NSMutableArray * arrrayMutData;


@property(nonatomic,assign) NSInteger page;//歌曲的页数
@end

@implementation LSZAudioSearchContentVC
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.page = 1;
    [self setDataSearch:self.page];
    [LCFloatingWindow sharedInstance].hidden = YES;
}
#pragma mark - 歌曲搜索Music/search
-(void)setDataSearch :(NSInteger)page
{
    self.page = 1;
    [self getMusicData:self.page];
    if (_isPop) {
        [self reloadTableView];//执行POP的方法，比如你POP回来后需要刷新表格。
    }else{
        //执行PUSH进来时的方法。
    }
    _isPop=YES;//将标志设置为YES。
}
#pragma mark - 歌曲的数据
-(void)getMusicData :(NSInteger)page
{
    NSString * string = [[NSString alloc]init];
    if ([self.type isEqualToString:@"5"]) {
        string = @"2";
    }else if ([self.type isEqualToString:@"2"]){
        string = @"";
    }else{
        string = self.type;
    }
    [LSZRequestResolutionDic AudioAearchResults:self.searchKeyword type:string page:[NSString stringWithFormat:@"%zd",(long)page] :^(BOOL isOK, NSString * str, LSZTabAudioSearchResultsManager *mg) {
        if(isOK == YES) {
            if (page == 1) {
                [self.arrrayMutData removeAllObjects];
                [self.arrrayMutData addObjectsFromArray:mg.arrayData];
                if(mg.arrayData.count == 0){
                    if (vcResults ==  nil) {
                        vcResults = [[LSZEmptyDataVC alloc]init];
                        [vcResults showWithView:self.tableViewResults];
                        self.tableViewResults.mj_footer.hidden = YES;
                    }
                }
            }else{
                if(mg.arrayData.count == 0){
                    [self.tableViewResults.mj_footer endRefreshingWithNoMoreData];
                }
                [self.arrrayMutData addObjectsFromArray:mg.arrayData];
            }
            [self.tableViewResults reloadData];
        }else{
            [self initWithtring:str];
            if (self.page != 1) {
                self.page = self.page-1;
            }
        }
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _isPop=YES;
    self.arrrayMutData = [[NSMutableArray alloc]init];

    [self setAudioUI];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
//刷新当前的cell数据
-(void)reloadTableView{
    [self.tableViewResults reloadData];
    if (_LCPlayer.kstatus == LCMusicPlayerStatusPlaying) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"LCPlayStatusStartAnimatingNotification" object:self userInfo:nil];
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrrayMutData.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (ScreenWidth == 320) {
        return 45;
    }else if(ScreenWidth == 375){
        return 50;
    }
    else {
        return 58;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0001;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UITableViewHeaderFooterView * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:@"cell"];
    }
    return cell;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([self.type isEqualToString:@"2"]){
        return [self audioTableView:tableView cellForRowAtIndexPath:indexPath];
    }else if ([self.type isEqualToString:@"1"]){
        return [self albumTableView:tableView cellForRowAtIndexPath:indexPath];
    }else{
        return [self singerTableView:tableView cellForRowAtIndexPath:indexPath];
    }
}
#pragma mark - 音频cell
-(UITableViewCell *)audioTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LSZNewWithPlusSignAudioTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZNewWithPlusSignAudioTableViewCell" forIndexPath:indexPath];
    LSZTabAudioSearchResultsMg * mg = nil;
    mg = self.arrrayMutData[indexPath.row];
    cell.labelNumber.text = [NSString stringWithFormat:@"%ld",(long)indexPath.row+1];
    cell.labelSong.text = NSStr(mg.title);
    cell.labelAlbums.text = [NSString stringWithFormat:@"%@ - %@",mg.artist_name,mg.album_name];//mg.click
    CGFloat widthLabel = [LSZSpecialPackaging getsTheAdaptiveWidth:cell.labelAlbums sizeMaxWidth:ScreenWidth-CGRectGetMinX(cell.labelAlbums.frame)];
    if (widthLabel< ScreenWidth-cell.butMove.frame.size.width-CGRectGetMinX(cell.labelAlbums.frame)-cell.imageViewHeadset.frame.size.width-40) {
        cell.imageViewHeadset.hidden = NO;
        cell.labelPlaysNumber.text = mg.click;
        cell.labelPlaysNumber.hidden = NO;
        //耳机
        [LSZSpecialPackaging adaptiveWidth:cell.labelAlbums str:cell.labelAlbums.text sizeMaxWidth:ScreenWidth-CGRectGetMinX(cell.labelAlbums.frame) sizeMaxHeight:cell.labelAlbums.frame.size.height];
        CGRect rect = cell.imageViewHeadset.frame;
        rect.origin.x = CGRectGetMaxX(cell.labelAlbums.frame);
        cell.imageViewHeadset.frame = rect;
        //次数
        CGRect rectPlays = cell.labelPlaysNumber.frame;
        rectPlays.origin.x = CGRectGetMaxX(cell.imageViewHeadset.frame)+2;
        rectPlays.size.width = ScreenWidth-CGRectGetMaxX(cell.imageViewHeadset.frame)-10;
        cell.labelPlaysNumber.frame = rectPlays;
        cell.labelPlaysNumber.text = [NSString stringWithFormat:@"%@",mg.click];
    }else{
        cell.imageViewHeadset.hidden = YES;
        cell.labelPlaysNumber.hidden = YES;

        CGRect rect = cell.labelAlbums.frame;
        rect.size.width = ScreenWidth-CGRectGetMaxX(cell.butAdd.frame)-45-5;
        cell.labelAlbums.frame = rect;
    }
    [cell didSelectRowCellWithIsSystemRed:NO];
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        cell.labelSong.attributedText = [ZNBAttributedString setAllText:cell.labelSong.attributedText.string andKeyWords:self.searchKeyword withKeyWordsColor:RGBColor(81, 122, 172) KeyWordsFont: cell.labelSong.font];
    }];
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        cell.labelAlbums.attributedText = [ZNBAttributedString setAllText:cell.labelAlbums.attributedText.string andKeyWords:self.searchKeyword withKeyWordsColor:RGBColor(81, 122, 172) KeyWordsFont: cell.labelAlbums.font];
    }];
    cell.butAdd.hidden = YES;
    cell.butMove.hidden = YES;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
#pragma mark - 专辑cell
-(UITableViewCell *)albumTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LSZAlbumDetailsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZAlbumDetailsTableViewCell" forIndexPath:indexPath];
    LSZTabAudioSearchResultsMg * mg = nil;
    mg = self.arrrayMutData[indexPath.row];
    [cell.imageViewCover sd_setImageWithURL:[NSURL URLWithString:mg.image] placeholderImage:[UIImage imageNamed:@"我的_设置_关于"]];
    cell.labelTitle.text     = mg.album_name;
    cell.labelCoverName.text = [NSString stringWithFormat:@"%@  共%@首",mg.singerName,mg.total_song];
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        cell.labelTitle.attributedText = [ZNBAttributedString setAllText:cell.labelTitle.attributedText.string andKeyWords:self.searchKeyword withKeyWordsColor:RGBColor(81, 122, 172) KeyWordsFont: cell.labelTitle.font];
    }];
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        cell.labelCoverName.attributedText = [ZNBAttributedString setAllText:cell.labelCoverName.attributedText.string andKeyWords:self.searchKeyword withKeyWordsColor:RGBColor(81, 122, 172) KeyWordsFont: cell.labelCoverName.font];
    }];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
#pragma mark - 歌手cell
-(UITableViewCell *)singerTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LSZSingerTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZSingerTableViewCell" forIndexPath:indexPath];
    LSZTabAudioSearchResultsMg * mg = nil;
    mg = self.arrrayMutData[indexPath.row];
    [cell.imageViewCover sd_setImageWithURL:[NSURL URLWithString:mg.image] placeholderImage:[UIImage imageNamed:@"我的_设置_关于"]];
    cell.labelTitle.text     = mg.artist_name;
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        cell.labelTitle.attributedText = [ZNBAttributedString setAllText:cell.labelTitle.attributedText.string andKeyWords:self.searchKeyword withKeyWordsColor:RGBColor(81, 122, 172) KeyWordsFont: cell.labelTitle.font];
    }];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - 切换歌
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    for (UIViewController *controller in self.navigationController.viewControllers) {
        if (![self.fromWhere isEqualToString:@"1"]) {
            if ([controller isKindOfClass:[LSZReleaseDynamicVC class]]) {
                if (self.arrrayMutData.count > indexPath.row) {
                    LSZTabAudioSearchResultsMg * mg = nil;
                    mg = self.arrrayMutData[indexPath.row];
                    LSZReleaseDynamicVC * A =(LSZReleaseDynamicVC *)controller;
                    A.resource = mg.id_id;
                    A.type = self.type;
                    if ([self.type isEqualToString:@"2"]) {
                        A.songName = mg.title;
                        A.authorOrAlbum = [NSString stringWithFormat:@"%@ - %@",mg.artist_name,mg.album_name];
                        A.cover_img = mg.cover_img;
                    }else if ([self.type isEqualToString:@"1"]){
                        A.songName = mg.album_name;
                        A.authorOrAlbum = [NSString stringWithFormat:@"%@  共%@首",mg.singerName,mg.total_song];
                        A.cover_img = mg.image;
                    }else{
                        A.songName = mg.artist_name;
                        A.authorOrAlbum = @"";
                        A.cover_img = mg.image;
                    }
                    [self.navigationController popToViewController:A animated:YES];
                }
            }
        }else{
            if ([controller isKindOfClass:[LSZReleasePrayerAndWitnessVC class]]) {
                if (self.arrrayMutData.count > indexPath.row) {
                    LSZTabAudioSearchResultsMg * mg = nil;
                    mg = self.arrrayMutData[indexPath.row];
                    LSZReleasePrayerAndWitnessVC * A =(LSZReleasePrayerAndWitnessVC *)controller;
                    A.resource = mg.id_id;
                    A.type = self.type;
                    if ([self.type isEqualToString:@"2"]) {
                        A.songName = mg.title;
                        A.authorOrAlbum = [NSString stringWithFormat:@"%@ - %@",mg.artist_name,mg.album_name];
                        A.cover_img = mg.cover_img;
                    }else if ([self.type isEqualToString:@"1"]){
                        A.songName = mg.album_name;
                        A.authorOrAlbum = [NSString stringWithFormat:@"%@  共%@首",mg.singerName,mg.total_song];
                        A.cover_img = mg.image;
                    }else{
                        A.songName = mg.artist_name;
                        A.authorOrAlbum = @"";
                        A.cover_img = mg.image;
                    }
                    [self.navigationController popToViewController:A animated:YES];
                }
            }
        }
    }
}
-(void)setAudioUI
{
    self.tableViewResults = [[UITableView alloc] initWithFrame:CGRectMake(0 , 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    self.tableViewResults.delegate = self;
    self.tableViewResults.dataSource = self;
    self.tableViewResults.estimatedRowHeight =0;
    self.tableViewResults.estimatedSectionFooterHeight =0;
    self.tableViewResults.estimatedSectionHeaderHeight =0;
    self.tableViewResults.separatorColor = divider;
    self.tableViewResults.separatorInset = UIEdgeInsetsMake(0, 20, 0, 20);
    self.tableViewResults.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    [self.view addSubview:self.tableViewResults];
    [self.tableViewResults registerClass:[LSZNewWithPlusSignAudioTableViewCell class] forCellReuseIdentifier:@"LSZNewWithPlusSignAudioTableViewCell"];
    [self.tableViewResults registerClass:[LSZAlbumDetailsTableViewCell class] forCellReuseIdentifier:@"LSZAlbumDetailsTableViewCell"];
    [self.tableViewResults registerClass:[LSZSingerTableViewCell class] forCellReuseIdentifier:@"LSZSingerTableViewCell"];

    self.tableViewResults.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.page = 1;
        //延时
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self getMusicData:self.page];
            [self.tableViewResults.mj_header endRefreshing];
        });
    }];
    self.tableViewResults.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.page++;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self getMusicData:self.page];
            [self.tableViewResults.mj_footer endRefreshing];
        });
    }];
}


@end
